#include <vector>
#include <algorithm>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        int n, m;
        cin >> n;
        vector<int> s1(n, 0);
        for (int i = 0; i < n; i++)
            cin >> s1[i];
        cin >> m;
        vector<int> s2(m, 0);
        for (int i = 0; i < m; i++)
            cin >> s2[i];
        vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
        vector<vector<int>> pos(n + 1, vector<int>(m + 1, 0));
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
            {
                if (s1[i] == s2[j] && s1[i] > pos[i][j])
                {
                    dp[i + 1][j + 1] = dp[i][j] + 1;
                    pos[i + 1][j + 1] = s1[i];
                }
                else
                {
                    if (dp[i + 1][j] > dp[i][j + 1])
                    {
                        dp[i + 1][j + 1] = dp[i + 1][j];
                        pos[i + 1][j + 1] = pos[i + 1][j];
                    }
                    else
                    {
                        dp[i + 1][j + 1] = dp[i][j + 1];
                        pos[i + 1][j + 1] = pos[i][j + 1];
                    }
                }
            }
        cout << dp[n][m] << endl;
        if(t) cout <<endl;
    }
    return 0;
}
